package com.xcc.gserver;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/")
public class GServer extends HttpServlet {
    /**
     * 储存位置
     */
    private File path;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        StartListener listener = StartListener.getInstance();
        if (listener == null) return;
        path = listener.getPath();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //不能访问
        if (path == null) {
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        String reqpath = req.getServletPath();
        //System.out.println("reqpath:" + reqpath);
        File reqfile = new File(path, reqpath);
        System.out.println("reqfile:" + reqfile.getAbsolutePath());
        if (!reqfile.exists()) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else if (reqfile.isDirectory()) {
            //resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            if (!reqpath.endsWith("/")) {
                resp.sendRedirect(req.getContextPath() + reqpath + "/");
                return;
            }
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=utf-8");
            try (PrintWriter wr = resp.getWriter()) {
                wr.println("<html><body>");
                wr.println("<h1>" + reqpath + "</h1>");
                wr.println("[Back] <a href='../'>..</a><br>");
                File[] fs = reqfile.listFiles();
                if (fs != null && fs.length > 0) {
                    for (File f : fs) {
                        if (f.isFile()) {
                            wr.println("[File] <a href='" + f.getName() + "'>" + f.getName() + "</a><br>");
                        } else {
                            wr.println("[Dir] <a href='" + f.getName() + "/'>" + f.getName() + "</a><br>");
                        }
                    }
                }
                wr.println("</body></html>");
            }
        } else {
            try (OutputStream out = resp.getOutputStream()) {
                Files.copy(reqfile.toPath(), out);
            }
        }
    }
}

